package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.BaseEntity;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.deviceData.IotMsgNotifyData;
import com.zzyl.nursing.dto.deviceData.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-10
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public void batchInsertDeviceData(String contentStr) {
        // 将contentStr 转换为对象
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        String notifyData = String.valueOf(jsonObject.get("notify_data"));
        IotMsgNotifyData iotMsgNotifyData = JSONUtil.toBean(notifyData, IotMsgNotifyData.class);

        // 通过设备ID查询数据库中是否含有数据
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotMsgNotifyData.getHeader().getDeviceId()));
        if (ObjectUtils.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }

        // 组装设备上报数据
        IotMsgService iotMsgService = iotMsgNotifyData.getBody().getServices().get(0);
        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(iotMsgService.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        //转入多个设备数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        Map<String, Object> properties = iotMsgService.getProperties();
        //遍历map集合，批量新增数据
        for (Map.Entry<String, Object> property : properties.entrySet()) {
            DeviceData deviceData = new DeviceData();
            BeanUtil.copyProperties(device, deviceData, "id");
            deviceData.setFunctionId(property.getKey());
            deviceData.setDataValue(property.getValue().toString());
            deviceData.setAlarmTime(eventTime);
            deviceDataList.add(deviceData);
        }
        //批量保存
        this.saveBatch(deviceDataList);

        // 存入redis
        redisCache.setCacheMapValue(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
    }
}
